
// System header files
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <string>
#include "ImgReader.h"

#define LINE_SIZE 512
using namespace std;
//#include <ifstream>
ImgReader::ImgReader(void)
{

}

ImgReader::~ImgReader(void)
{

}

void ImgReader::readImage(const char *fn, vector <int> &vertices, int &h,int &w,int &m)
{	
	char str [LINE_SIZE];				
	//char width	
	ifstream myfile;
	myfile.open(fn,ios::in);
	myfile.getline(str,LINE_SIZE,'\n');


	if(strcmp(str,"P2")!=0){
		cout << "File fomat is not pgm";
		exit(0);
	}else{ 
		myfile.getline(str,LINE_SIZE,'\n'); myfile.getline(str,LINE_SIZE,'\n');
		int pos =0;
		string strs = string(str);
		pos = strs.find(' ',0);
		h=atoi(strs.substr(pos+1,strs.length()-1).c_str());
		w =atoi(strs.substr(0,pos).c_str()); 			
		myfile.getline(str,LINE_SIZE,'\n');
		m=atoi(str);	
	}

	
	int *vertice = new int[w*5*h];  //reason for 5. each digit(max length 3) is represented by a char and spereated by 2 spaces. 
	char *line = new char[w*5];
	for(int j =0; j < h; j++)
	{
		
		myfile.getline(line,w*5,'\n');
		string temp = string(line);
		cout << temp <<"\n";
		int pos =0,len=0;

		for(int i =0; i < w; i++)
		{				
			len = temp.find(' ',pos)==string::npos? temp.length()-pos : temp.find(' ',pos)-pos;
			vertice[j*w+i]=atoi(temp.substr(pos,len).c_str());
			pos = temp.find_first_not_of(' ',pos+len);
			//pos = temp.find_first_not_of(' ',pos+len)==string::npos ? pos+len: temp.find_first_not_of(' ',pos+len);						
			//(i==w-1)? : pos = temp.find_first_not_of(' ',pos+len);
		}
		
				
	}

	for(int j =0; j < h; j++)
	{
		
			for(int i =0; i < w; i++)
			{
				
				vertices.push_back(vertice[j*w+i]);				
			}
			cout << '\n';
				
	}

}



